package com.sts.jdbc.impl;

import com.sts.jdbc.JdbcOperation;
import com.sts.jdbc.model.ColumnInfo;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class MysqlOperationImpl implements JdbcOperation {

    @Override
    public List<String> getAllSchema(Connection connection) {
        List<String> schemaList = new ArrayList<>();

        try (
                Connection con = connection;
                ResultSet resultSet = con.getMetaData().getCatalogs()
        ) {
            while (resultSet.next()) {
                String tableCat = resultSet.getString("TABLE_CAT");
                schemaList.add(tableCat);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        return schemaList;
    }

    @Override
    public List<String> getAllTable(Connection connection, String schema) {
        List<String> tableList = new ArrayList<>();

        try (
                Connection con = connection;
                ResultSet resultSet = con.getMetaData().getTables(schema, null, null, new String[]{"TABLE"})
        ) {
            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                tableList.add(tableName);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        return tableList;
    }

    @Override
    public Map<String, ColumnInfo> getTableAllPrimaryKeyColumn(Connection connection, String schema, String table) {
        Map<String, ColumnInfo> columnInfoPrimaryKeyMap = new LinkedHashMap<>();

        try (Connection con = connection) {
            DatabaseMetaData metaData = con.getMetaData();

            try (ResultSet resultSet = metaData.getPrimaryKeys(schema, null, table)) {
                while (resultSet.next()) {
                    String columnName = resultSet.getString("COLUMN_NAME");
                    short keySeq = resultSet.getShort("KEY_SEQ");
                    String pkName = resultSet.getString("PK_NAME");

                    columnInfoPrimaryKeyMap.put(columnName.toUpperCase(),
                            new ColumnInfo(
                                    columnName,
                                    keySeq,
                                    pkName
                            )
                    );
                }

            }
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        return columnInfoPrimaryKeyMap;
    }
}
